(function($, com) {
	var state = app.getState();
	var uid = state.user_id;
	$.ajaxSettings.async = false;
	localStorage.removeItem('roomlist' + uid);
	localStorage.removeItem('indexlist' + uid);
	com.get = function(type) {
		var type = type || 'index';
		//chatset(type);
		var mydata = JSON.parse(localStorage.getItem(type + 'list' + uid) || '[]');
		
		if(!mydata || mydata.length < 1) {
			mydata = chatset(type);
		}
		return mydata;
	}
	//var chatdata = chat.get();

	function chatset(type) {
		if(type == 'index') {
			var urlget = apiurl + 'chat/getindex?user_id=' + uid;
		} else {
			var urlget = apiurl + 'chat/getRoomIndex?user_id=' + uid;
		}

		var rt = [];
		$.get(urlget, function(res) {
			if(res.status < 1) {
				return;
			}
			var chatlist = res.list;
			console.log(JSON.stringify(chatlist));
			if(chatlist && chatlist.length > 0) {
				rt = chatparseList(chatlist, type);
			}
		});
		return rt;
	}

	function chatparseList(setdata, type) {
		var cdata = [];
		var allnum = 0,
			i = 0,
			j = 0,
			len = setdata.length,
			fids = {};
		for(; i < len; i++) {
			var fid = setdata[i]['f_id'];
			fids[fid] = setdata[i];
		}
		for(var p in fids) {
			var ld = fids[p];
			//console.log(type);
			/*
			if(ld['ctype'] == 1 && type != 'index') {
				type = 'index';
			}
			if(type != 'room' && ld['ctype'] == 2) {
				type = 'room';
			}*/
			//name
			if(ld['f_name']) {
				allnum = allnum + ld.msgnum;
				ld['msg'] = app.parseMainMsg(ld['t_msg'], ld['r_type']);
				cdata.push(ld);
			}

		}
		//console.log('last');
		//console.log(JSON.stringify(cdata));
		localStorage.setItem(type + 'chatnum' + uid, allnum);
		localStorage.setItem(type + 'list' + uid, JSON.stringify(cdata));
		return cdata;
	}
	com.HTMLDecode = function(text) {
		var temp = document.createElement("div");
		temp.innerHTML = text;
		var output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}
	/**
	 * 同步多条聊天信息
	 * @param {Object} rtinfo
	 */
	com.updateList = function(rtinfo, type) {
		//console.log(JSON.stringify(rtinfo));
		if(rtinfo && rtinfo.length > 0) {
			//var chatdata = JSON.parse(localStorage.getItem('mainlist' + uid) || '[]');
			var chatdata = com.get(type),
				add = {},
				old = {},
				i = 0,
				p = 0,
				rtlen = rtinfo.length,
				ctlen = chatdata.length;
			//同步chatdata
			for(; i < rtlen; i++) {
				var fid = rtinfo[i]['f_id'];
				add[fid] = rtinfo[i];
			}
			//console.log(JSON.stringify(add));
			//先同步存在的
			for(; p < ctlen; p++) {
				var fid = chatdata[p]['f_id'];
				old[fid] = fid;
				if(fid in add) {
					var istop = chatdata[p]['istop'] || 0;
					chatdata[p] = add[fid];
					chatdata[p]['istop'] = istop;
					//chatdata[p]['msg'] = app.parseMainMsg(chatdata[p]['t_msg'], chatdata[p]['r_type']);
				}
			}
			//再添加不存在的
			for(var c in add) {
				if(old[c] === undefined) {
					chatdata.push(add[c]);
				}
			}
			chatparseList(chatdata, type);
			//renderlist(chatdata);
		}
	}
	/**
	 * 同步一条聊天信息
	 * @param {Object} rtinfo
	 */
	com.updateSay = function(rtinfo, type) {
		//console.log(JSON.stringify(rtinfo));
		//console.log(type);
		if(rtinfo) {
			//var chatdata = JSON.parse(localStorage.getItem('mainlist' + uid) || '[]');
			var chatdata = com.get(type),
				i = 0,
				len = chatdata.length,
				has = false;
			if(type == 'room') {
				for(; i < len; i++) {
					if(rtinfo['t_id'] == chatdata[i]['f_id']) {

						has = true;
						chatdata[i]['add_time'] = rtinfo['add_time'];
						chatdata[i]['t_msg'] = rtinfo['t_msg'];
						if(uid == chatdata[i]['f_id']) {
							chatdata[i]['msgnum'] = 0;

						} else {
							chatdata[i]['msgnum'] = parseInt(chatdata[i]['msgnum']) + 1;
						}
						chatdata[i]['f_name'] = rtinfo['t_name'];
						chatdata[i]['r_type'] = rtinfo['r_type'];
						break;
					}
				}
			}else{
				for(; i < len; i++) {
					//别人发给我的
					if(rtinfo['f_id'] == chatdata[i]['f_id']) {
						console.log(uid);
						console.log(chatdata[i]['t_id']);
						has = true;
						chatdata[i]['add_time'] = rtinfo['add_time'];
						chatdata[i]['t_msg'] = rtinfo['t_msg'];
						if(uid == chatdata[i]['t_id']) {
							chatdata[i]['msgnum'] = 0;
						}else{
							chatdata[i]['msgnum'] = parseInt(chatdata[i]['msgnum']) + 1;
						}
						chatdata[i]['f_name'] = rtinfo['f_name'];
						chatdata[i]['r_type'] = rtinfo['r_type'];
						break;
					}
				}
			}

			if(has === false) {
				chatdata.push(rtinfo);
			}
			//console.log(JSON.stringify(chatdata));
			chatparseList(chatdata, type);
			//renderlist(chatdata);
		}
	};

	com.setDataByField = function(room_id, field, val, type) {
		var chatdata = com.get(type),
			i = 0,
			len = chatdata.length;
		for(; i < len; i++) {
			if(chatdata[i]['f_id'] == room_id) {
				chatdata[i][field] = val;
			}
		}
		chatparseList(chatdata, type);
		//localStorage.setItem('mainlist' + uid, JSON.stringify(chatdata));
	};
	/**
	 * 进入聊天室后同步聊天列表页
	 * @param {Object} msg
	 * @param {Object} type
	 * @param {Object} uptime
	 */
	/*
	chat.venderToIndex = function(msg, type, uptime) {
		//var maindata = JSON.parse(localStorage.getItem('mainlist' + uid) || '[]');
		var allnum = 0;
		var uptime = uptime || 0;
		var has = false;
		var showmsg = app.parseMainMsg(msg, type);
		var now = Date.parse(new Date()) / 1000;
		for(var i = 0; i < chatdata.length; i++) {
			if(chatdata[i]['f_id'] == im.roomId) {
				chatdata[i]['msgnum'] = 0;
				if(uptime > 0) {
					chatdata[i]['add_time'] = now;
				}

				chatdata[i]['msg'] = showmsg;
				has = true;
				//maindata[i]['show_time'] = app.dateStr(maindata[i]['add_time']);
			}
			allnum = allnum + chatdata[i]['msgnum'];
		}
		
		if(has === false) {
			var add = {
				'f_id': roomId,
				'f_name': chatName,
				'ctype': roomType,
				'f_header': header,
				'msgnum': 0,
				'add_time': now,
				'msg': showmsg
			};
			chatdata.push(add);
		}
		chatparseList(chatdata);
	};*/
	com.delOne = function(room_id, type) {
		var chatdata = com.get(type),
			i = 0,
			len = chatdata.length,
			news = [];

		for(; i < len; i++) {
			if(chatdata[i]['f_id'] !== room_id) {
				news.push(chatdata[i]);
			}
		}
		chatparseList(news, type);
	};
	//长按消息框
	function msgIndexTap(e) {
		//console.log('触发长按');
		var el = this,
			btns = [{
				title: "删除聊天",
				tags: 'del'
			}],
			msgnum = el.getAttribute('msgnum') || 0,
			istop = el.getAttribute('istop') || 0,
			f_id = el.getAttribute('f_id'),
			ctype = el.getAttribute('ctype'),
			datatype = ctype == 1 ? 'index' : 'room';
		//console.log(datatype);
		if(msgnum > 0) {
			btns.push({
				title: '标为已读'
			});
		} else {
			btns.push({
				title: '标为未读'
			});
		}
		if(istop > 0) {
			btns.push({
				title: '取消置顶'
			});
		} else {
			btns.push({
				title: '设为置顶'
			});
		}
		plus.nativeUI.actionSheet({
			title: "操作",
			cancel: "取消",
			buttons: btns
		}, function(e) {
			//console.log("User pressed: " + e.index);
			var id = e.index;
			console.log(id);
			if(id > 0) {
				//删除
				if(id == 1) {
					com.delOne(f_id, datatype);
					el.parentNode && el.parentNode.removeChild(el);

				}
				else if(id == 2) {
					var badge = el.querySelector('.mui-badge');
					var setval = 0;
					if(msgnum && msgnum > 0) {
						if(badge) {
							badge.parentNode.removeChild(badge);
						}
					} else {
						setval = 1;
						if(!badge) {
							var badge = document.createElement("span");
							var targetprent = el.querySelector('.mui-table-cell');
							var targetimg = targetprent.querySelector('img.mui-media-object');
							badge.setAttribute('class', 'mui-badge');
							badge.innerHTML = 1;
							targetprent.insertBefore(badge, targetimg.nextSibling);
						} else {
							badge.innerHTML = 1;
						}
					}
					el.setAttribute('msgnum', setval);
					com.setDataByField(f_id, 'msgnum', setval, datatype);
				}
				else if(id == 3) {
					var mainarea = document.querySelector('#main-area'),
						toparea = document.querySelector('#top-area'),
						setval = 0;
					if(istop > 0) {
						var node = el.cloneNode(true);
						node.setAttribute('istop', setval);
						mainarea.insertBefore(node, mainarea.childNodes[0]);
						el.parentNode.removeChild(el);
					} else {
						setval = 1;
						var node = el.cloneNode(true);
						node.setAttribute('istop', setval);
						toparea.appendChild(node);
						el.parentNode.removeChild(el);
					}
					
					com.setDataByField(f_id, 'istop', setval, datatype);
				}
				return;
				//li.parentNode.removeChild(li);
			}else{
				return;
			}
		});
	};

	function openchatWin() {

		var titleName = this.getAttribute('title');
		var headerImg = this.querySelector('img').getAttribute('src');
		var roomId = this.getAttribute('room-id');
		var roomType = this.getAttribute('room-type');
		//location.href = 'pages/chat/chat_index.html?chatTitle=' + titleName + '&chatHeader=' + headerImg + '&roomId=' + roomId + '&roomType' + roomType; 
		mui.openWindow({
			url: '/pages/chat/chat_index.html',
			id: 'chatbox',

			show: {
				autoShow: true,
				aniShow: 'slide-in-right',
				duration: 100
			},
			extras: {
				chatTitle: titleName,
				chatHeader: headerImg,
				roomId: roomId,
				roomType: roomType
			}
		});

	}

	com.renderlist = function(type) {
		var chatdata = com.get(type);
		app.arrSort(chatdata, 'add_time');
		var renddata = [];
		var topdata = [];
		var maindata = [];
		for(var i in chatdata) {
			chatdata[i]['show_time'] = app.dateStr(chatdata[i]['add_time']);
			var headerimg = chatdata[i]['f_header'];
			if(chatdata[i]['ctype'] == 2) {
				chatdata[i]['f_header'] = 'static/images/qun.png';
			} else {
				if(headerimg && headerimg.indexOf('upload') !== -1) {
					chatdata[i]['f_header'] = serverurl + 'upload/avatar/' + chatdata[i]['f_id'] + '.jpg';
				} else {
					chatdata[i]['f_header'] = 'static/images/1.png';
				}

			}
			chatdata[i]['msg'] = chat.HTMLDecode(chatdata[i]['msg']);
			if(chatdata[i]['istop'] && chatdata[i]['istop'] > 0) {
				topdata.push(chatdata[i]);
			} else {
				maindata.push(chatdata[i]);
			}

		}
		if(topdata.length > 0) {
			document.querySelector("#top-area").innerHTML = template('main-templete', {
				"mainlist": topdata
			});
		}
		if(maindata.length > 0) {
			document.querySelector("#main-area").innerHTML = template('main-templete', {
				"mainlist": maindata
			});
		}
		$('.mui-content').on('longtap', '.mui-table-view-cell', msgIndexTap);
		$('.mui-content').on('tap', '.mui-slider-handle', openchatWin);

	}
	
}(mui, window.chat = {}));